/*
 * Copyright 2003,2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.jakubiak.jpa.translator.serializer;

/**
 *
 * @author Antek
 */
public class PlainSerializer implements Serializer {

    public <T> T deserialize(Class<T> type, String string) {
        if (!isSimplyType(type)) {
            return new ObjectStreamSerializer().deserialize(type, string);
        } else {
            if (String.class.equals(type)) {
                return (T)string;
            } else if (Long.class.equals(type)) {
                return (T)Long.valueOf(string);
            } else if (Integer.class.equals(type)) {
                return (T)Integer.valueOf(string);
            } else if (Short.class.equals(type)) {
                return (T)Short.valueOf(string);
            } else if (Boolean.class.equals(type)) {
                return (T)Boolean.valueOf(string);
            }
            throw new UnsupportedOperationException("This type is not yet implemented - developer error");
        }
    }

    public <T> String serialize(Class<T> type, T object) {
        if (!isSimplyType(type)) {
            return new ObjectStreamSerializer().serialize(type, object);
        } else {
            return object.toString();
        }
    }
    
    
    
    private Class[] SIMPLY_TYPES = {String.class, Long.class, Integer.class, Short.class, Boolean.class};

    protected boolean isSimplyType(Class type) {
        for (Class c : SIMPLY_TYPES) {
            if (c.equals(type)) {
                return true;
            }
        }
        return false;
    }
}
